<?php
// +----------------------------------------------------------------------------
// | Tke团队版权所属 [三十年河东三十年河西,莫欺少年穷.!]
// +----------------------------------------------------------------------------
// | Copyright (c) 2014 http://www.itdaodan.com All rights reserved.
// +----------------------------------------------------------------------------
// | Author: Cruise<jiangyu@hrbjjhh.com>
// +----------------------------------------------------------------------------
/**
 +------------------------------------------------------------------------------
* 天天特卖模型
+------------------------------------------------------------------------------
* @version   1.0
* @since 2015-12-07
+------------------------------------------------------------------------------
*/
namespace Home\Model;

class ShopModel {

    public $error;//记录最后一次错误信息
    
    /**
     * @todo 特卖详情-商品详情数据
     * @param int     $goods_id  商品id
     * @param boolean $is_mobile 手机端验证
     * @return array|boolean
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function goodsData($goods_id,$is_mobile,$width = 375,$height = 270){
    	$goods_id = (int)$goods_id;
    	if($goods_id == 0){
    		$this->error = '商品id有误！';
    		return false;
    	}
    	if(!is_bool($is_mobile)){
    		$this->error = '手机PC判断有误！';
    		return false;
    	}
    	if(!is_int($width)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($height)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	$obj = D('Admin/ServiceApi');
    	$goods_data = $obj->getGoodsShow($goods_id); //取得商品信息
    	if(empty($goods_data)){ //数据为空给与没有商品信息提示
    		$this->error = '暂无商品信息！';
    		return false;
    	}
    	//pc或手机端懒加载商品内容
    	if($is_mobile){
            $goods_data['goods_content'] = preg_replace('/<img([\s\S]+?)src\s*=([\s\S]+?)>/i', "<img$1data-echo=$2 width='100%' src='' />", $goods_data['goods_content']);
            $goods_data['goods_thumb'] = getPictureThumb($goods_data['pic_id'],$width,$height);
            $goods_data['buy_link'] = U('/Shop/buy',array('id'=>$goods_data['goods_id']));
    	}else{
    		$goods_data['goods_content'] = preg_replace('/<img([\s\S]+?)src\s*=([\s\S]+?)>/i', "<img$1data-original=$2 src=$2 class='lazy'/>", $goods_data['goods_content']);
    	}
    	
    	$map['shop_id'] = $goods_data['shop_id'];
    	$goods_data['shop_name'] = M('Shop')->where($map)->getField('shop_name');
    	//手机的时候才有的数据，主要因为手机和PC渲染方式不一样
    	if($goods_data['goods_type'] == 1 && $is_mobile){
    		$goods_data['state_2'] = $this->stateTime($goods_data['promotion_start_time'],$goods_data['promotion_end_time'],$goods_data['promotion_stock']);
    		$goods_data['data_cutedown_1'] = $goods_data['promotion_start_time']-NOW_TIME >0 ? $goods_data['promotion_start_time']-NOW_TIME : 0;
    		$goods_data['data_cutedown_2'] = $goods_data['promotion_end_time']-NOW_TIME >0 ? $goods_data['promotion_end_time']-NOW_TIME : 0;
    		$goods_data['promotion_stock'] = randGoodsOrderCount($goods_data['promotion_stock']);
    		$goods_data['shop_price'] = $goods_data['promotion_price'];
    	}else if($goods_data['goods_type'] != 1 && $is_mobile){
    		$goods_data['state_2'] = $goods_data['goods_stock']>0 ? 1 :3;
    		$goods_data['promotion_stock'] = randGoodsOrderCount($goods_data['goods_stock']);
    	}
    	$goods_data['goods_discount'] = number_format($goods_data['shop_price']/$goods_data['market_price']*10,1);
    	$goods_data['shop_link'] = U('/Shop/brand',array('id'=>$goods_data['shop_id']));
    	return $goods_data;
    }
    
    /**
     * @todo 特卖详情时间管理
     * @param string $start 促销开始时间
     * @param string $end   促销结束时间
     * @return array|null   已经结束返回null
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function goodsTime($start,$end){
    	$start = (int)$start;
    	$end = (int)$end;
    	//时间判断
    	$not_begin = $start - NOW_TIME;//距离开始时间
    	$not_end = $end - NOW_TIME;//距结束时间差
    	if($not_begin > 0){
    		//距开始时间赋初始值
    		//$time['day'] = sprintf( "%'02s",floor($not_begin/86400));
    		$time['hour'] = sprintf( "%'02s",floor($not_begin/3600));
    		$time['min'] = sprintf( "%'02s",floor($not_begin%3600/60));
    		$time['sec'] = sprintf( "%'02s",floor($not_begin%60));
    	}elseif($not_end > 0){
    		//距结束时间赋初始值
    		//$time['day'] = sprintf( "%'02s",floor($not_end/86400));
    		$time['hour'] = sprintf( "%'02s",floor($not_end/3600));
    		$time['min'] = sprintf( "%'02s",floor($not_end%3600/60));
    		$time['sec'] = sprintf( "%'02s",floor($not_end%60));
    	}else{
    		return null;
    	}
	    return $time;
    }
     
    /**
     * @todo 特卖详情时间管理
     * @param string $start     促销开始时间
     * @param string $end       促销结束时间
     * @param $promotion_stock  库存
     * @return int   0未开始 1立即购买 2已结束 3已售罄
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    private function stateTime($start,$end,$promotion_stock){
    	$start = (int)$start;
    	$end = (int)$end;
    	$promotion_stock = (int)$promotion_stock;
    	//时间判断
    	$not_begin = $start - NOW_TIME;//距离开始时间
    	$not_end = $end - NOW_TIME;//距结束时间差
    	if($not_begin > 0){
    		//距开始时间赋初始值
    		return 0;//未开始。未开始时不考虑库存
    	}elseif($not_end > 0){
    		return $promotion_stock>0 ? 1 : 3;//正ing
    	}
    	return $promotion_stock>0 ? 2 : 3;//已结束
    }
    
    /**
     * @todo   特卖详情页推荐信息
     * @param  array          $map    查询条件
     * @param  int            $num    查询数量
     * @return array|boolean
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function detailRecommendList($map,$num){
    	if(empty($map)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($num)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	$recommend_ids = $recommend_data = array();
    	$obj = D('Admin/ServiceApi');
    	$field = 'goods_id,goods_name,goods_title,market_price,shop_price,goods_deposit,
    			  goods_unit,goods_stock,goods_type,pic_id,goods_introduction';
    	//取出推荐商品内容
    	$recommend_data = $obj->getSaleGoodsNum($map,$field,$num);
    	if(empty($recommend_data)){
    		return null;
    	}
    	//推荐商品goods_id
    	$recommend_ids = array_column($recommend_data, 'goods_id');
    	//获取商品id对应的促销信息
    	$goods_promotion = $obj->getSaleGoodsPromotion($recommend_ids);
    	//推荐列表促销信息附加（4条）
    	foreach ($recommend_data as $key=>$val){
    		if(isset($goods_promotion[$val['goods_id']])){
    			$recommend_data[$key]['promotion_id'] = $goods_promotion[$val['goods_id']]['promotion_id'];
    			$recommend_data[$key]['promotion_price'] = $goods_promotion[$val['goods_id']]['promotion_price'];
    			$recommend_data[$key]['promotion_stock'] = $goods_promotion[$val['goods_id']]['promotion_stock'];
    			$recommend_data[$key]['promotion_start_time'] = $goods_promotion[$val['goods_id']]['promotion_start_time'];
    			$recommend_data[$key]['promotion_end_time'] = $goods_promotion[$val['goods_id']]['promotion_end_time'];
    			$recommend_data[$key]['promotion_pic_id'] = $goods_promotion[$val['goods_id']]['promotion_pic_id'];
    		}
    	}
    	return $recommend_data ;
    }
    
    /**
     * @todo   特卖首页爆款数据
     * @param  array     $map        条件
     * @param  int       $num        条数
     * @param  boolean	 $isMobile   验证
     * @param  string	 $order		   排序
     * @return array|boolean		 state_1商品图片对应状态    state_2按钮对应状态
     * 								   其中 state_2 字段 分为促销商品和正常商品
     * 					   			   正常商品对应值    1立即购买    3已售罄
     * 					   			   促销商品对应值    0即将开始   1立即购买   2已结束   3已售罄
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function getGoodsList($map,$num=16,$is_mobile=true,$width = 468,$height = 280,$order = 'sort desc, goods_id desc'){
    	if(empty($map)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($num)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_bool($is_mobile)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($width)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($height)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	$obj = D('Admin/ServiceApi');
    	$field_goods = 'goods_id,shop_id,goods_name,goods_type,goods_title,market_price
    					,shop_price,goods_stock,goods_deposit,pic_id,goods_introduction,goods_unit';
    	
    	$field_promotion = 'goods_id,pic_id,promotion_price,promotion_stock
    					,promotion_start_time,promotion_end_time';
    	$goods_list = $obj->getSaleGoodsNum($map,$field_goods,$num,$order); //取得爆款商品
    	if(empty($goods_list)){
    		return array();
    	}
    	$goods_list_ids = array_column($goods_list, 'goods_id');
    	$promotion_list = $obj->getSaleGoodsPromotion($goods_list_ids,$field_promotion);
    	if(!$is_mobile){
    		$goods_tags = $obj->getSaleGoodsTag($goods_list_ids);
    	}
    	foreach ($goods_list as $key=>$val){
    		//加入促销信息
    		if(isset($promotion_list[$val['goods_id']])){
    			$goods_list[$key]['shop_price'] = $promotion_list[$val['goods_id']]['promotion_price'];
    			$goods_list[$key]['goods_thumb'] = getPictureThumb($promotion_list[$val['goods_id']]['pic_id'],$width,$height);
    			$goods_list[$key]['promotion_stock'] = randGoodsOrderCount($promotion_list[$val['goods_id']]['promotion_stock']);//剩余户数
    			//商品状态调取外部方法，原来清晰地写法见备份iWeb2016.03.05
    			$goods_list[$key]['state_1'] = $goods_list[$key]['state_2'] = $this->stateTime($promotion_list[$val['goods_id']]['promotion_start_time'],$promotion_list[$val['goods_id']]['promotion_end_time'],$goods_list[$key]['promotion_stock']);
    			//兼容老版手机端
    			$goods_list[$key]['data_cutedown_1'] = $promotion_list[$val['goods_id']]['promotion_start_time']-NOW_TIME >0 ? $promotion_list[$val['goods_id']]['promotion_start_time']-NOW_TIME : 0;
    			$goods_list[$key]['data_cutedown_2'] = $promotion_list[$val['goods_id']]['promotion_end_time']-NOW_TIME >0 ? $promotion_list[$val['goods_id']]['promotion_end_time']-NOW_TIME : 0;
    		}else{
    			$goods_list[$key]['pic_id'] = $val['pic_id'];
    			$goods_list[$key]['goods_thumb'] = getPictureThumb($val['pic_id'],$width,$height);
    			$goods_list[$key]['promotion_stock'] = randGoodsOrderCount($goods_list[$key]['goods_stock']);//剩余户数
    			//正常商品图片和按钮显示
    			$goods_list[$key]['state_1'] = $goods_list[$key]['state_2'] = $goods_list[$key]['promotion_stock']>0 ? 1 :3;
    		}
    		$goods_list[$key]['goods_discount'] = number_format($goods_list[$key]['shop_price']/$val['market_price']*10,1);
     		$goods_list[$key]['goods_introduction'] = msubstr(nl2br($val['goods_introduction']),0,100,'utf-8',false);
    		$goods_list[$key]['goods_name'] = $is_mobile ? msubstr($val['goods_name'].$val['goods_title'],0,22,'utf-8',false) : msubstr($val['goods_name'].$val['goods_title'],0,48,'utf-8',false);
    		$goods_list[$key]['follow_count'] = randGoodsFollowCount($val['goods_id']);//关注数
    		$goods_list[$key]['goods_link'] = U('/Shop/goods',array('id'=>$val['goods_id']));
    		//兼容老版手机端
    		$goods_list[$key]['cutedown_str'] = '';
    		//加入标签
    		if(isset($goods_tags[$val['goods_id']])){
    			$goods_list[$key]['tags'] = array_slice($goods_tags[$val['goods_id']],0,5);
    		}
    		//手机端的图片都显示正常图片（不显示促销图片）
    		if($is_mobile === true){
    			$goods_list[$key]['goods_thumb'] = getPictureThumb($val['pic_id'],$width,$height);
    		}
    		unset($goods_list[$key]['goods_stock'],$goods_list[$key]['pic_id'],$goods_list[$key]['shop_id']);
    	}
    	return $goods_list;
    }
    
    /**
     * @todo 获取特卖首页的分类信息
     * @return array
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function getClassify(){
    	$obj = D('Admin/ServiceApi');
    	$classify = $obj->getSalePositionList(32,2048);
    	if(empty($classify)){
    		return array();
    	}
    	$classify[0] = '全部';
    	return $classify;
    }
    
    /**
     * @todo   特卖首页推荐数据（异步请求）
     * @param  array     $map  		   	  	查询条件
     * @param  int       $page 		 	  	页码
     * @param  int       $page_count 	  	显示条数
     * @param  boolean	 $isMobile   		验证
     * @param  string	 $order		  		排序
     * @return array	   其中 state_2 字段 分为促销商品和正常商品
     * 					   正常商品对应值    1立即购买    3已售罄
     * 					   促销商品对应值     0即将开始   1立即购买   2已结束   3已售罄
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function saleRecommendList($map,$page,$page_count=40,$is_mobile=true,$width = 226,$height = 226,$order = 'sort desc, goods_id desc'){
    	//定义初始返回值
    	$call_back = array(
    			'status' => 0,
    			'info'   => '更多宝贝即将上架，敬请期待！'
    	);
    	if(empty($map)){
    		return $call_back;
    	}
    	if(!is_int($page)){
    		return $call_back;
    	}
    	if(!is_bool($is_mobile)){
    		return $call_back;
    	}
    	if(!is_int($width)){
    		return $call_back;
    	}
    	if(!is_int($height)){
    		return $call_back;
    	}
    	$obj = D('Admin/ServiceApi');
    	$field_goods = 'goods_id,shop_id,goods_name,goods_title,market_price,shop_price,goods_stock,goods_deposit,pic_id';
    	$field_promotion = 'goods_id,pic_id,promotion_price,promotion_stock';
    	$recommend_list = $obj->getSaleGoods($map,$page,$page_count,$field_goods); //取得爆款商品
    	if(empty($recommend_list)){
    		return $call_back;
    	}
    	$recommend_list_ids = array_column($recommend_list, 'goods_id');
    	$promotion_list = $obj->getSaleGoodsPromotion($recommend_list_ids,$field_promotion);
    	foreach($recommend_list as $key=>$val){
    		$recommend_list[$key]['goods_name'] = msubstr($val['goods_name'].$val['goods_title'],0,20,'utf-8',false);
    		$recommend_list[$key]['follow_count'] = randGoodsFollowCount($val['goods_id']);//关注数
    		$recommend_list[$key]['goods_link'] = U('/Shop/goods',array('id'=>$val['goods_id']));
    		$recommend_list[$key]['goods_thumb'] = getPictureThumb($val['pic_id'],$width,$height);
    		if(isset($promotion_list[$val['goods_id']])){
    			$recommend_list[$key]['promotion_stock'] = randGoodsOrderCount($promotion_list[$val['goods_id']]['promotion_stock']);//剩余户数
    			$recommend_list[$key]['shop_price'] = $promotion_list[$val['goods_id']]['promotion_price'];//关注数
    		}else{
    			$recommend_list[$key]['promotion_stock'] = randGoodsOrderCount($val['goods_stock']);//剩余户数
    		}
    		$recommend_list[$key]['state_2'] = $recommend_list[$key]['promotion_stock']>0 ? 1 : 3;//正常商品状态对应    1立即购买 3已售罄
    		unset($recommend_list[$key]['goods_id'],$recommend_list[$key]['pic_id'],$recommend_list[$key]['goods_stock']);
    	}
    	$call_back = array(
    			'status' => 1,
    			'info'   => '操作成功！',
    			'data'   => $recommend_list
    	);
    	return $call_back;
    }
    
    /**
     * @todo   特卖店铺信息
     * @param  int   $id 	店铺id
     * @return array
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function getSaleBrand($id,$is_mobile = false,$width = 226,$height = 226){
    	$id = (int)$id;
    	if(!is_bool($is_mobile)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(empty($id)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($width)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($height)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	$obj = D('Admin/ServiceApi');
    	$shop_data = $obj->getShopInfo($id); //取得店铺信息
    	if(empty($shop_data)){
    		$this->error = '暂无店铺！';
    		return false;
    	}
    	$shop_data_new = array(
    			'shop_id'			=> $shop_data['shop_id'],
    			'shop_name' 		=> $shop_data['shop_name'],
    			'shop_introduction' => $shop_data['shop_introduction'],
    			'shop_address' 		=> $shop_data['shop_address'],
    			'cover_id' 			=> getPictureThumb($shop_data['cover_id'],$width,$height),
    			'shop_link'			=> U('/Shop/allBrand')
    			
    	);
    	return  $shop_data_new;
    }
    
    /**
     * @todo   获取店铺list
     * @param  array    $map where 条件
     * @param  string   $field 需要查询的字段
     * @param  string   $order 排序
     * @return array
     * @author Cruise <jiangyu@hrbjjhh.com>
     */
    public function getShopList($map,$width = 360,$height = 160,$field = true, $order = 'sort desc, shop_id desc'){
    	if(empty($map)){
    		$map['status'] = 1;
    	}
    	if(!is_int($width)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	if(!is_int($height)){
    		$this->error = '参数错误！';
    		return false;
    	}
    	$obj = D('Admin/ServiceApi');
    	$shop_category_list = $obj->getShopCategory();
    	$shop_list = $obj->shopList($map);
    	if(empty($shop_category_list) || empty($shop_list)){
    		return array();
    	}
    	$shop_list_new = array();
    	foreach ($shop_category_list as $k=>$v){
    		$shop_list_new[$v['shop_category_id']] = array(
    				'shop_category_id'=>$v['shop_category_id'],
    				'shop_category_name'=>$v['shop_category_name'],
    				'children'=> array()
    		);
    	}
    	foreach ($shop_list as $key=>$val){
    		if($val['shop_category_id'] != 0){
    			$shop_list_new[$val['shop_category_id']]['children'][] = array(
    					'shop_id'=>$val['shop_id'],
    					'logo_id'=>getPictureThumb($val['logo_id'],$width,$height),
    					'shop_link'=>U('/Shop/brand',array('id'=>$val['shop_id']))
    			);
    		}
    	}
    	//返回的数组将使用数值键，从 0 开始并以 1 递增
    	return array_values($shop_list_new);
    }
    
    /**
     * @todo   获取每天10点倒计时
     * @return int   时间戳差值
     * @author Crusie<jiangyu@hrbjjhh.com>
     */
    public function everyDayTen(){
    	$every_day = strtotime(date('Y-m-d 09:59:59'));//当天10点
    	$now = time();
    	$final = $now-$every_day;
    	if($final < 0){
    		return $every_day - $now;
    	}
    	$tomorrow = strtotime(date("Y-m-d 09:59:59",strtotime("+1 day")));//第二天10点
    	return  $tomorrow - $now;
    }
    
    
    /**
     * @todo 返回最后一次错误信息
     * @return string
     * @author PHP@妖孽 <dino_ma@163.com>
     */
    public function getError(){
    	return $this->error;
    }
    
}
